<?php


namespace app\cms\oauth\controller;


use app\community\boot\oauth2\oauthBoot;
use iflow\Container\implement\annotation\tools\data\Inject;
use iflow\Response;
use iflow\Router\Controller;
use iflow\Router\implement\Request\PostMapping;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Grant\ClientCredentialsGrant;
use Psr\Http\Message\ResponseInterface;

#[Controller('%oauth2%/authorization')]
class ClientCredentialsGrantController {

    #[Inject]
    public oauthBoot $oauthBoot;

    /**
     * Client credentials grant
     * @return ResponseInterface|Response
     */
    #[PostMapping]
    public function clientCredentialsAccessToken(): ResponseInterface|Response
    {
        try {
            return $this->oauthBoot
                -> enableGrantType(
                    new ClientCredentialsGrant()
                )
                -> getOauthServer()
                -> respondToAccessTokenRequest(
                    request() -> getServerRequestPsr7(),
                    response() -> getResponsePsr7()
                );
        } catch (OAuthServerException | \Exception $exception) {
            return message() -> server_error($exception -> getCode(), $exception -> getMessage());
        }
    }

}